import { ref } from 'vue';

export const usePagination = () => {
  const list = ref<any[]>([]);
  const total = ref(0);
  const queryParams = ref({
    pageNumber: 1,
    pageSize: 10,
  });
  const columns = ref<any[]>([]);
  const loading = ref(false);
  return { list, total, queryParams, columns, loading };
};

export const useSortable = () => {
  const tableRef = ref();
  const sortList = ref<any[]>([]);
  const onSortChangeHandler = (sortData: any, callback: () => void) => {
    // sortList.value.find(el=>el.)
    const { prop, order } = sortData;
    const index = sortList.value.findIndex((el) => el.prop === prop);
    if (!order && index !== -1) {
      sortList.value.splice(index, 1);
      callback();
      return;
    }
    if (index !== -1) {
      sortList.value.splice(index, 1, { prop, order });
    } else {
      sortList.value.push({ prop, order });
    }
    callback();
  };
  const headerCellClassName = (data: any) => {
    const { column } = data;
    const item = sortList.value.find((el: any) => el.prop === column.property);
    if (!item) {
      if (column.sortable && column.order) {
        column.order = null;
      }
      return;
    }
    column.order = item.order;
    return '';
  };
  const orderBys = () => {
    return sortList.value.map((el: any) => {
      const { prop, order } = el;
      return {
        field: prop.replace(/Text$/, ''),
        asc: order === 'ascending' ? 1 : -1,
      };
    });
  };
  return {
    tableRef,
    sortList,
    onSortChangeHandler,
    headerCellClassName,
    orderBys,
  };
};
